/**   
* @Title: IndexController.java 
* @Package com.nebula.upms.controller 
* @Description: TODO(用一句话描述该文件做什么) 
* @author zhanghui   
* @date 2016年2月1日 下午6:12:42 
* @version V1.0   
*/
package com.nebula.upms.admin.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nebula.common.util.IpUtils;
import com.nebula.common.util.MD5Util;
import com.nebula.common.util.PropertyUtil;
import com.nebula.upms.admin.service.IndexService;
import com.nebula.upms.admin.support.UpmsSession;
import com.nebula.upms.service.model.vo.UpmsAppSystemVO;
import com.nebula.upms.service.model.vo.UpmsUserVO;
import com.nebula.upms.service.support.constant.UpmsFinal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.nebula.common.framework.BaseController;


import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;

/** 
* @ClassName: IndexController 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author zhanghui
* @date 2016年2月1日 下午6:12:42 
*  
*/
@Controller
public class IndexController extends BaseController {
	
	@Autowired
	private IndexService indexService;

	@RequestMapping(value={"/login"})
	public String login(HttpServletRequest request,Model model){
		super.paramsToModel(request,model,new String[]{"error"});
		this.initSystemConfig(model);
		return "/framework/login";
	}
	
	
	
	@RequestMapping(value={"/loginin"})
	@ResponseBody
	public String loginin(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> params=super.paramsToMap(request);
		
		
		if(null!=params.get("loginName")&&null!=params.get("loginPassword")){
			String loginName=params.get("loginName").toString();
			String loginPassword=params.get("loginPassword").toString();
			UpmsUserVO upmsUserVO=this.indexService.loginIn(loginName, loginPassword);
			if(null!=upmsUserVO){
				
				String token= MD5Util.MD5(upmsUserVO.getStaffId()+new Date().toString());
				Cookie cookie = new Cookie(UpmsFinal.UPMS_USERTOKEN,token);
				cookie.setMaxAge(UpmsFinal.SESSION_TIME_OUT);
				cookie.setPath("/");
				response.addCookie(cookie);
				
				UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
				this.indexService.saveUserSession(upmsUserVO, userAgent, token, IpUtils.getIpAddr(request));
				return "success";
			}
			
			return "error";
		}else{
			return "error";
		}
		
	}

	@RequestMapping(value={"/","/index"})
	public String index(HttpServletRequest request,Model model){
		Map<String,Object> cookieMap=super.cookies2Map(request);
		String systemId=null;
		if(null!=cookieMap.get("UPMS_SYSTEMID")){
			systemId=cookieMap.get("UPMS_SYSTEMID").toString();
		}
		UpmsUserVO upmsUserVO= UpmsSession.currentUser(request);
		UpmsAppSystemVO currentAppSystemVO=null;
		
		if(null!=upmsUserVO){
			upmsUserVO=this.indexService.getUpmsUserVOByStaffId(upmsUserVO.getStaffId());
			model.addAttribute("upmsUserVO", upmsUserVO);
			List<UpmsAppSystemVO> systemList=upmsUserVO.getUpmsAppSystemVOList();
			currentAppSystemVO=systemList.get(0);
			
			for (UpmsAppSystemVO upmsAppSystemVO : systemList) {
				if(upmsAppSystemVO.getAppSystemId().equals(systemId)){
					currentAppSystemVO=upmsAppSystemVO;
					break;
				}
			}
			
			model.addAttribute("currentAppSystemVO", currentAppSystemVO);
			this.initSystemConfig(model);
			return "/framework/index";
		}else{
			return "redirect:/login?error=timeout";
		}
	}
	
	@RequestMapping(value={"/exit"})
	public String exit(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> cookieMap=this.cookies2Map(request);
		try {
			String token= (String) cookieMap.get(UpmsFinal.UPMS_USERTOKEN);
			this.setUserCookieNull(response);
			this.indexService.deleteUserSession(token);
		} catch (Exception e) {
			
		}
		return "redirect:/login";
	}
	
	@RequestMapping(value={"/heartbeat"})
	@ResponseBody
	public String heartbeat(HttpServletRequest request,HttpServletResponse response,Model model){
		Map<String,Object> cookieMap=this.cookies2Map(request);
		
		String token=null;
		if(null!=cookieMap.get(UpmsFinal.UPMS_USERTOKEN)){
			token= (String) cookieMap.get(UpmsFinal.UPMS_USERTOKEN);
			boolean isTokenAlive=this.indexService.isTokenAlive(token);
			if(!isTokenAlive){
				this.setUserCookieNull(response);
				this.indexService.deleteUserSession(token);
				return "timeout";
			}
		}else{
			//没有token 不做任何处理
			return "notoken";
		}
		return "success";
	}
	
	
	@RequestMapping(value={"/loginerror"})
	public String loginerror(HttpServletRequest request,Model model){
		Map<String,Object> params=super.paramsToMap(request);
		super.paramsToModel(request, model,new String[]{"error"});
		return "/framework/loginerror";
	}
	
	
	
	
	
	private void setUserCookieNull(HttpServletResponse response){
		Cookie cookie = new Cookie(UpmsFinal.UPMS_USERTOKEN, null);
		cookie.setMaxAge(-1);
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	
	@RequestMapping(value={"/home"})
	public String home(HttpServletRequest request,Model model){
		this.initSystemConfig(model);
		return "/framework/home";
	}
	
	private void initSystemConfig(Model model){
		boolean isalert=false;
		String systemName="";
		try {
			String environment= PropertyUtil.getProperty("config.environment");
			model.addAttribute("environment", environment);
			
			if(environment.equals("dev")){
				systemName="开发环境";
			}
			if(environment.equals("test")){
				systemName="测试环境";
			}
			if(environment.equals("pre")){
				systemName="预生产环境";
			}
			if(environment.equals("prod")){
				systemName="";
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("isalert", isalert);
		model.addAttribute("systemName", systemName);
	}
	
}
